package services;

import dao.UserInfoDao;
import models.UserInfo;
import utils.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/8
 * Time:15:33
 **/
@WebServlet("/log")
public class LogServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //定义返回给前端的参数
        int succ = -1;//成功返回1
        String msg = "";
        //获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //业务逻辑处理
        //登录：操作数据库查询用户
        if(username != null && !username.equals("") &&
                password != null && !password.equals("")) {
            UserInfoDao userInfoDao = new UserInfoDao();
            try {
                UserInfo userInfo = userInfoDao.find(username, password);
                if(userInfo.getId()>0){
                    succ = 1;//表示查到了
                    //将信息存放到session
                    HttpSession session = req.getSession();
                    //将信息存放到当前session
                    session.setAttribute("userinfo",userInfo);
                }else{
                    succ = 0;
                    msg = "用户名或密码输入错误！";
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }else{
            msg = "参数不完整！";
        }
        //返回结果
        HashMap<String,Object> ret = new HashMap<>();
        ret.put("succ",succ);
        ret.put("msg",msg);
        ResultUtils.write(resp,ret);
    }
}
